<?php
namespace App\Http\Controllers\Company;

use App\Models\Examination;
use App\Models\Questions;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\CompanyJobs;
use App\Models\ExaminationHistory;
/**
 *
 * @author Joker
 *        
 */
class ExaminationController extends CompanyController
{
    
    public function __construct()
    {
        parent::__construct();
    }
    
    /**
     * 
     * @see \App\Http\Controllers\Company\CompanyController::index()
     */
    public function index()
    {
        if(empty($this->userinfo->company_id))
            return redirect(url('/company/center/companyinfo-default'));
        
        $examinations = Examination::where('company_id','=',$this->userinfo->company_id)->paginate(20);
        return view('company.exam')
                ->with('examinations', $examinations);
    }
    
    /**
     * 新建试卷
     */
    public function create()
    {
        if(empty($this->userinfo->company_id))
            return redirect(url('/company/center/companyinfo-default'));
        
        $questions = Questions::where('company_id','=',$this->userinfo->company_id)->get();
        
        return view('company.examdetails')
                ->with('questions', $questions);
    }
    
    /**
     * 编辑
     * @param integer $id
     */
    public function show($id)
    {
        if(empty($this->userinfo->company_id))
            return redirect(url('/company/center/companyinfo-default'));
        
        $questions = Questions::where('company_id','=',$this->userinfo->company_id)->get();
        $examination = Examination::find($id);
        if(empty($examination))
        {
            return $this->formatJson('error','资源不存在！');
        }
        
        $selected = array_fetch($examination->questions->toArray(),'id');
        
        return view('company.examdetails')
                ->with('result',$examination)
                ->with('selected',$selected)
                ->with('questions', $questions);
    }
    /**
     * 保存试卷
     * @param  Request  $request
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'name'          => 'required|max:255',
            'score_limit'   => 'required|integer',
            'score'         => 'required|integer',
            'times'         => 'required',
        ]);
        $examination_id = $request->get('id', 0);
        /*试题ID数组*/
        $question_ids = $request->get('question_id');
        $post = array_except($request->all(), ['_token', 'id', 'question_id']);
        $post['question_count'] = count($question_ids);
        $post['company_id'] = $this->userinfo->company_id;
        DB::beginTransaction();
        try{
            if($examination_id > 0 AND !empty($post)) {
                $company_examina = Examination::find($examination_id);
                foreach ($post as $key => $val) {
                    $company_examina->$key = $val;
                }
                $company_examina->save();
            } else{
                $company_examina = Examination::firstOrCreate($post);
            }
            $company_examina->questions()->sync($question_ids);
            DB::commit();
        }catch (\PDOException $e){
            Log::info(['企业保存试卷失败'=>$e->getMessage()]);
            DB::rollback();
            return $this->formatJson('error','保存试卷失败！');
        }
        return $this->formatJson('success','创建数据成功,请前往关联相关职位！',$company_examina,url('/company/center/exams'));
    }
    
    /**
     * 删除
     * @param integer $examination_id
     */
    public function destroy($examination_id)
    {
    
        $examination = Examination::where(['id'=>$examination_id,'company_id'=>$this->userinfo->company_id])->first();
        if(empty($examination))
            return $this->formatJson('error','资源不存在！');
        $hasjob = CompanyJobs::where('exam_id','=',$examination_id)->first();
        if(!empty($hasjob))
            return $this->formatJson('error','已有职位关联该考试，请先取消关联！');
        
        DB::beginTransaction();
        try{
            $examination->delete();
            $examination->questions()->detach();
            DB::commit();
            return $this->formatJson('success','试卷 ['. str_limit($examination->name, 15) . '] 删除成功!');
        }catch (\PDOException $e){
            DB::rollback();
            Log::info(['删除试卷失败'=>$e->getMessage()]);
            return $this->formatJson('error','删除试卷失败！');
        }
    
    }
    
    /**
     * 用户考试记录 
     */
    public function history()
    {
        $ehistory = ExaminationHistory::where('company_id','=',$this->userinfo->company_id)->paginate(20);
        return view('company.ehistory')->with('ehistory',$ehistory);
    }
}